<template>
  <div>
    <input type="file" @change="handleFileChange" accept=".docx" />

    <!-- 弹窗遮罩层 -->
    <div v-if="showModal" class="modal-overlay">
      <div class="modal-content" @click.stop>
        <!-- 固定关闭按钮 -->
        <button class="close-btn" @click="closeModal">✖</button>

        <!-- Word 预览内容 -->
        <div class="word-preview" v-if="previewHtml" v-html="previewHtml"></div>
      </div>
    </div>
  </div>
</template>

<script>
import mammoth from "mammoth";

export default {
  name: "WordPreview",
  data() {
    return {
      showModal: false,
      previewHtml: null,
    };
  },
  methods: {
    async handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      const arrayBuffer = await this.readFileAsArrayBuffer(file);
      const result = await mammoth.convertToHtml({ arrayBuffer });

      this.previewHtml = result.value;
      this.showModal = true;
    },
    readFileAsArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject(reader.error);
        reader.readAsArrayBuffer(file);
      });
    },
    closeModal() {
      this.showModal = false;
    }
  }
};
</script>

<style scoped>
input {
  margin-bottom: 20px;
}

/* 遮罩层：铺满全屏 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6); /* 半透明黑色背景 */
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 弹窗内容容器：铺满整个页面 */
.modal-content {
  background: #fff;
  width: 100%;
  height: 100%;
  padding: 30px 40px 20px 20px;
  box-sizing: border-box;
  position: relative;
  overflow-y: auto;
}

/* 关闭按钮：固定在右上角 */
.close-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  font-size: 24px;
  background: none;
  border: none;
  color: #555;
  cursor: pointer;
  z-index: 10000;
  transition: color 0.2s ease;
}

.close-btn:hover {
  color: #e74c3c; /* hover 变红更醒目 */
}
</style>
